import { stringify } from 'qs'
import { Data, HTTP_PREFIX, HTTPS_PREFIX } from '../index';
import { appConfig } from './app';


function getParamsStringify(url: string, params?: Data) {
  if (params) {
    return url + stringify(params, {
      addQueryPrefix: true,
      allowDots: true,
      indices: false,
      skipNulls: true,
    })
  } else {
    return url
  }
}

export function getAppUrl(options: any = {}): string {
  const url = options.url ?? ''
  if (url) {
    if (url.includes('?')) {
      throw new Error('url 中不能包含 ? 号，请使用 params 代替')
    } else if (url.startsWith(HTTP_PREFIX) || url.startsWith(HTTPS_PREFIX)) {
      return getParamsStringify(url, options.params)
    }
  }
  const appKey = options.app || appConfig.app.key
  if (!appKey) {
    throw new Error('appKey 不能为空')
  }
  const uri = appConfig.app.keys[appKey]
  if (!uri) {
    throw new Error(`未配置 ${appKey}`)
  }
  return getParamsStringify(uri + url, options.params)
}
